<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50">
    <div class="max-w-md w-full space-y-8 p-8">
      <div class="text-center">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
        <h2 class="text-2xl font-bold text-gray-900 mb-2">正在处理登录...</h2>
        <p class="text-gray-600">请稍候，正在验证您的Google账户</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { userApi } from '~/public/utils/api'

// 设置页面标题
useHead({
  title: 'Google登录回调 - 碳关税平台'
})

onMounted(async () => {
  try {
    // 获取URL中的参数
    const urlParams = new URLSearchParams(window.location.search)
    const token = urlParams.get('token')
    const username = urlParams.get('username')
    
    if (!token) {
      console.error('No token received')
      
      // ⭐ 检查是否在弹出窗口中
      if (window.opener && !window.opener.closed) {
        // 在弹窗中：发送错误消息
        window.opener.postMessage({
          type: 'GOOGLE_LOGIN_ERROR',
          error: 'No token received'
        }, window.location.origin)
        window.close()
      } else {
        // 正常页面流程
        alert('未收到授权令牌，请重试')
        await navigateTo('/login')
      }
      return
    }
    
    // Step 1: Store token first (required for getUserInfo API)
    localStorage.setItem('token', token)
    
    // Step 2: Get complete user information
    let userData = null
    try {
      const userInfoResult = await userApi.getUserInfo()
      
      if (userInfoResult.data) {
        userData = {
          fullName: userInfoResult.data.fullName || username,
          name: username,
          email: userInfoResult.data.email || username,
          position: userInfoResult.data.position,
          phone: userInfoResult.data.phone,
          companyName: userInfoResult.data.companyName,
          companyAddress: userInfoResult.data.companyAddress
        }
      } else {
        throw new Error('Failed to get user info')
      }
    } catch (userInfoError) {
      console.error('Failed to get user info:', userInfoError)
      // Fallback: use basic info if getUserInfo fails
      userData = {
        fullName: username,
        name: username,
        email: username
      }
    }
    
    // ⭐ 检查是否在弹出窗口中
    if (window.opener && !window.opener.closed) {
      // 在弹出窗口中：发送消息给父窗口
      window.opener.postMessage({
        type: 'GOOGLE_LOGIN_SUCCESS',
        user: userData,
        token: token
      }, window.location.origin)
      
      // 显示成功提示（可选）
      const { $toast } = useNuxtApp()
      $toast.success('Login successful! Closing window...')
      
      // 延迟关闭弹窗，让用户看到提示
      setTimeout(() => {
        window.close()
      }, 1000)
    } else {
      // 正常页面流程：使用 auth 插件登录并跳转
      const { $auth, $toast } = useNuxtApp()
      $auth.login(userData, token)
      $toast.success('Google登录成功！')
      await navigateTo('/')
    }
    
  } catch (error) {
    console.error('Google login error:', error)
    
    // ⭐ 检查是否在弹出窗口中
    if (window.opener && !window.opener.closed) {
      // 在弹窗中：发送错误消息
      window.opener.postMessage({
        type: 'GOOGLE_LOGIN_ERROR',
        error: error.message || 'Unknown error'
      }, window.location.origin)
      window.close()
    } else {
      // 正常页面：显示错误
      alert('Google登录失败，请重试')
      await navigateTo('/login')
    }
  }
})
</script> 